package org.mobile.servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mobile.beans.Order;
import org.mobile.beans.User;
import org.mobile.logic.OrderLogic;
import org.mobile.logic.UserLogic;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet(name = "Login", urlPatterns = { "/Login" })
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public LoginServlet() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.getSession().removeAttribute("user");
		request.getSession().removeAttribute("cart");
		response.sendRedirect("index.jsp");
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 * log out
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User user= null;
		String login= request.getParameter("login");
		String password= request.getParameter("password");
		if(!login.isEmpty()){
			if(!password.isEmpty()){
				user= UserLogic.getInstance().logIn(login, password);
				if(user != null){
					request.getSession().setAttribute("user", user);
					user.setUserOrders((ArrayList<Order>) OrderLogic.getInstance().getOrders(user.getId()));
					request.setAttribute("message", "Zalogowano");
					request.getRequestDispatcher("index.jsp").forward(request, response);
				}
				else {
					request.setAttribute("error", "Niezalogowano");
					request.getRequestDispatcher("errPage.jsp").forward(request, response);
				}
				
			}
			else {
				request.setAttribute("error", "Niezalogowano");
				request.getRequestDispatcher("errPage.jsp").forward(request, response);
			}
		}
		else {
			request.setAttribute("error", "Niezalogowano");
			request.getRequestDispatcher("errPage.jsp").forward(request, response);
		}
	}

}
